<template>
  <div class="minPageCon">
      <div class="des">
          <p v-if="userType=='personal'">전문가가 도와주는</br>당신의 2번째 커리어,</br><b>지금 시작해볼까요?</b></p>
          <p v-else>기업에서 필요로하는</br>경력이 풍부한 인재,</br><b>지금 만나볼까요?</b></p>
          <img src="@images/login_bg.png" alt="">
      </div>
      <div class="box">
        <h1>비밀번호 찾기</h1>
        <p class="info">
          가입시 입력한<br/>
          <b>아이디와 휴대폰 번호</b>를<br/>
          입력하세요.
        </p>
        <el-form class="loginFrm forgotFrm" :model="forgotFrm" :rules="rules" ref="forgotFrm">
            <el-form-item prop="email">
                <el-input type="email" placeholder="아이디(이메일)" v-model="forgotFrm.email" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item prop="phone" :error="errors.phone">
              <el-col :span="17">
                <el-input placeholder="휴대폰번호(‘-’는 빼고 입력해주세요)" v-model="forgotFrm.phone" autocomplete="off"></el-input>
              </el-col>
              <el-col :span="7">
                <el-button class="minBtn" v-show="showTime" @click="sendCode" plain>인증번호발송</el-button>
                <el-button class="minBtn" v-show="!showTime" disabled>{{sendTime}}초</el-button>
              </el-col>
            </el-form-item>
            <el-form-item prop="verification_code" :error="errors.ver_code">
              <el-col :span="17">
                <el-input type="number" placeholder="인증번호 6자리" v-model="forgotFrm.verification_code" autocomplete="off"></el-input>
              </el-col>
            </el-form-item>
            <el-form-item>
                <el-button :loading="loading" type="primary" class="subBtn" @click="submitForm('forgotFrm')">확인</el-button>
            </el-form-item>
        </el-form>
      </div>
  </div>
</template>

<script>
import { mapState, mapActions } from "vuex";
import { retrievePassword,sendVerCodeByPwd } from '@/api';
import { Local } from '@/utils'
import { setToken } from '@/utils/auth'

export default {
  name:'',
  components:{},
  props:[],
  data(){
    let _this=this;
    var validateMobile = (rule, value, callback) => {
      if (value==='') {
        callback(new Error('휴대폰번호를 입력해주세요.'));
      } else if(!value.match( /^[0-9]{3}[0-9]{4}[0-9]{4}$/ )) {
        callback(new Error('정상적인 전화번호를 입력해주세요.'));
      }else{
        if(_this.errors.phone){
          callback(new Error(_this.errors.phone));
        }else{
          callback();
        }
      }
    };
    var validateEmail = (rule, value, callback) => {
      if (value==='') {
        callback(new Error('아이디를 입력해 주세요.'));
      } else if(!value.match(/^[a-zA-Z0-9_-|.]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/)) {
        callback(new Error('정확한 이메일 주소를 입력하세요.'));
      }else{
        callback();
      }
    };
    return {
      userType:'',
      loading:false,
      showTime: true,
      sendTime: '',
      timer: null,
      errors:{
        phone:'',
        ver_code:''
      },
      forgotFrm: {
        email:'',
        phone:'',
        verification_code:'',
      },
      rules: {
        email: [
          { required: true, validator: validateEmail, trigger: 'change' }
        ],
        phone: [
          { required: true, validator: validateMobile, trigger: 'blur' }
        ],
        verification_code: [
          { required: true, message: '인증번호를 입력해주세요.', trigger: 'change' }
        ],
      }
    }
  },
  computed:{},
  created(){
    this.userType = this.$route.query.userType || 'personal';
  },
  mounted(){},
  methods:{
      ...mapActions(['setUserToken']),
      submitForm(formName) {
        let that=this;
        this.$refs[formName].validate(async (valid,error) => {
          if (valid) {
            that.loading = true;
            let res = await retrievePassword(that.forgotFrm);
            if (res.code == 200) {
              that.loading = false;
              setToken(res.data.token);
              that.setUserToken(res.data.token);
              that.$router.replace({ path:'/resetPwd',query:{userType:that.userType}})
            }else{
              that.loading = false;
              let _msg='가입이 되지않은 회원정보 입니다. 다시한번 확인해주세요.'
              // code -400:user does not exist
              if(res.code == -2){
                _msg = '인증번호가 틀렸습니다. 다시한번 확인해주세요.';
              }
              that.$alert(_msg, '알림', {
                confirmButtonText: '확인'
              });
            }
          } else {
            return false;
          }
        });
      },
      sendCode(){
        let _this=this;
        if(this.errors.phone){
          _this._send();
          return false;
        }
        this.$refs.forgotFrm.validateField('phone',function(err){
          if(err===''){
            _this._send();
          }
        });
      },
      async _send(){
          let res = await sendVerCodeByPwd({phone:this.forgotFrm.phone});
          if (res.code == 200) {
            const TIME_COUNT = 180;
            if (!this.timer) {
                this.sendTime = TIME_COUNT;
                this.showTime = false;
                this.timer = setInterval(() => {
                if (this.sendTime > 0 && this.sendTime <= TIME_COUNT) {
                    this.sendTime--;
                } else {
                    this.showTime = true;
                    clearInterval(this.timer);
                    this.timer = null;
                }
                }, 1000);
            }
            this.errors.phone='';
          }else{
            if(res.code == -600){
              this.errors.phone="휴대폰번호가 틀렸습니다.  다시한번 확인해주세요."
            }else{
              this.errors.ver_code="이미 가입한 휴대폰번호 입니다."
            }
          }
      }
  },
  watch:{}
}
</script>
<style lang="scss" scoped>
  @import "css/user.scss";
</style>
